package com.lucher.mes.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lucher.mes.common.Tools;
import com.lucher.mes.common.Uuid;
import com.lucher.mes.dao.QuartzjobMapper;
import com.lucher.mes.po.Productworkorder;
import com.lucher.mes.po.Quartzjob;
import com.lucher.mes.po.Week;
import com.lucher.mes.po.Workorder;
import com.lucher.mes.quartz.QuartzManager;
import com.lucher.mes.quartz.RollcallJob;

@Controller
@RequestMapping("/quartzJob")  
public class QuartzJobController extends BaseController{
	private static Logger logger = Logger.getLogger(QuartzJobController.class);
	@Autowired
	private QuartzjobMapper quartzjobDao;
	/**
	 * 查询信息
	 */
	@RequestMapping(value = "/findByList")
	public String findByList(Quartzjob form) {
		return "quartzjob/findQuartzjobList";
	}
	
	/**
	 * 查询信息Json
	 */
	@ResponseBody
	@RequestMapping(value = "/findListJson")
	public Map<String, Object> findListJson(Quartzjob form) {
		//封装JSon的Map
		Map<String, Object> result = new HashMap<String, Object>(); 
		result.put("code", "0");
		List<HashMap<String, Object>> objectlist = new ArrayList<HashMap<String, Object>>();
		
		Integer total = quartzjobDao.findByCount(form);
		List<Quartzjob> list = quartzjobDao.findByListForPage(form);
		
		for (Quartzjob quartzjob : list) {
			HashMap<String, Object> objectMap = new HashMap<String, Object>();
			
			objectMap.put("id", quartzjob.getId());
			objectMap.put("jobname", quartzjob.getJobname());
			objectMap.put("targetclassname", quartzjob.getTargetclassname());
			objectMap.put("cronexpression", quartzjob.getCronexpression());
			
			String cronexpression = Tools.getStr(quartzjob.getCronexpression());
			String[] cronexpressionArr = cronexpression.split(" ");
			if(cronexpressionArr != null && cronexpressionArr.length > 5){
				String weekcodes = cronexpressionArr[5];
				String[] weekcodeArr = weekcodes.split(",");
				//循环所有的工位机信息
				String expressionname_week = "";
				//SUN，MON，TUE，WED，THU，FRI，SAT
				
				List<Week> weeklist = new ArrayList<Week>();
				weeklist.add(new Week("MON","星期一"));
				weeklist.add(new Week("TUE","星期二"));
				weeklist.add(new Week("WED","星期三"));
				weeklist.add(new Week("THU","星期四"));
				weeklist.add(new Week("FRI","星期五"));
				weeklist.add(new Week("SAT","星期六"));
				weeklist.add(new Week("SUN","星期天"));
				for (Week week : weeklist) {
					for (String selectedweek : weekcodeArr) {
						if(week.getWeekcode().equals(selectedweek)){
							expressionname_week = expressionname_week + week.getWeekname() + " ";
							week.setPageSelected(true);
						}else{
							continue;
						}
					}
				}
				
				String cronexpressionname = expressionname_week + cronexpressionArr[2] + "时" + cronexpressionArr[1] +"分  执行一次";
				
				objectMap.put("cronexpressionname", cronexpressionname);
			}
			
			objectMap.put("jobstatus", quartzjob.getJobstatus());
			objectMap.put("runonholiday", quartzjob.getRunonholiday());
			objectMap.put("createtime", StringUtils.isEmpty(quartzjob.getCreatetime())?"":Tools.getStr(quartzjob.getCreatetime()).substring(0, 19));
			objectMap.put("creatername", quartzjob.getCreatername());
			objectMap.put("updatetime", StringUtils.isEmpty(quartzjob.getUpdatetime())?"":Tools.getStr(quartzjob.getUpdatetime()).substring(0, 19));
			objectMap.put("updatername", quartzjob.getUpdatername());
			objectMap.put("remark", quartzjob.getRemark());
			
			objectlist.add(objectMap);
		}
		
		result.put("count", total);
		result.put("data", objectlist);
		return result;
	}

	/**
	 * 添加信息初始化
	 * 
	 * @return
	 */
	@RequestMapping(value = "/addInit")
	public String addInit(Quartzjob form, Model model) {
		//查询所有的周期信息
		List<Week> weeklist = new ArrayList<Week>();
		
		//SUN，MON，TUE，WED，THU，FRI，SAT
		weeklist.add(new Week("MON","星期一"));
		weeklist.add(new Week("TUE","星期二"));
		weeklist.add(new Week("WED","星期三"));
		weeklist.add(new Week("THU","星期四"));
		weeklist.add(new Week("FRI","星期五"));
		weeklist.add(new Week("SAT","星期六"));
		weeklist.add(new Week("SUN","星期天"));
		model.addAttribute("weeklist", weeklist);
		return "quartzjob/addQuartzjob";
	}

	/**
	 * 新增
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value = "/save")
	public Map<String,Object>  save(Quartzjob form) {
		
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		
		String uuid = Uuid.generateShortUuid();
		form.setJobname(uuid);
		
		String hour = form.getHour();
		
		String minute = form.getMinute();
		
		//新添加星期几
		String weekcodes = form.getWeekcodes();
		if(StringUtils.isBlank(weekcodes)){
			responseJson.put("flag", "0");//操作失败
			responseJson.put("msg", "操作失败，请先选择星期几");
			return responseJson;
		}
		
		String cronexpression = "0 " + minute + " " + hour + " ? * "+ weekcodes;
		
		//赋值定时表达式
		form.setCronexpression(cronexpression);
		
		//赋值添加时间
		form.setCreatetime(Tools.getCurrentTime());
		
		//保存材料信息
		Integer quartzjobId = quartzjobDao.insertSelective(form);
		
		//加入定时任务管理中
		QuartzManager.addJob(form.getJobname(), RollcallJob.class, form.getCronexpression());
		
		responseJson.put("flag", "1");//操作成功
		responseJson.put("msg", "操作成功");
		
		return responseJson;
	}

	/**
	 * 更新初始化
	 */
	@RequestMapping(value = "/updateInit")
	public String updateInit(Quartzjob form, Model model) {
		Quartzjob quartzjob = quartzjobDao.selectByPrimaryKey(form.getId());
		
		String cronexpression =  Tools.getStr(quartzjob.getCronexpression());
		String[] cronexpressionArr = cronexpression.split(" ");
		if(cronexpressionArr != null && cronexpressionArr.length > 5){
			quartzjob.setMinute(cronexpressionArr[1]);
			quartzjob.setHour(cronexpressionArr[2]);
			
			String weekcodes = cronexpressionArr[5];
			String[] weekcodeArr = weekcodes.split(",");
			
			//循环所有的工位机信息
			String expressionname_week = "";
			
			//SUN，MON，TUE，WED，THU，FRI，SAT
			
			List<Week> weeklist = new ArrayList<Week>();
			weeklist.add(new Week("MON","星期一"));
			weeklist.add(new Week("TUE","星期二"));
			weeklist.add(new Week("WED","星期三"));
			weeklist.add(new Week("THU","星期四"));
			weeklist.add(new Week("FRI","星期五"));
			weeklist.add(new Week("SAT","星期六"));
			weeklist.add(new Week("SUN","星期天"));
			for (Week week : weeklist) {
				for (String selectedweek : weekcodeArr) {
					if(week.getWeekcode().equals(selectedweek)){
						expressionname_week = expressionname_week + week.getWeekname() + " ";
						week.setPageSelected(true);
					}else{
						continue;
					}
				}
			}
			model.addAttribute("weeklist", weeklist);
			
			String cronexpressionname = expressionname_week + cronexpressionArr[2] + "时" + cronexpressionArr[1] +"分  执行一次";
			quartzjob.setCronexpressionname(cronexpressionname);
		}
		form.setQuartzjob(quartzjob);

		return "quartzjob/updateQuartzjob";
	}

	/**
	 * 更新
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value = "/update")
	public Map<String,Object> update(Quartzjob form) {
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		Quartzjob oldQuartzjob = quartzjobDao.selectByPrimaryKey(form.getId());
		String hour = form.getHour();
		String minute = form.getMinute();
		
		//新添加星期几
		String weekcodes = form.getWeekcodes();
		if(StringUtils.isBlank(weekcodes)){
			responseJson.put("flag", "0");//操作失败
			responseJson.put("msg", "操作失败，请先选择星期几");
			return responseJson;
		}
		
		String cronexpression = "0 " + minute + " " + hour + " ? * "+ weekcodes;
		
		oldQuartzjob.setCronexpression(cronexpression);
		// 修改信息
		int flag = quartzjobDao.updateByPrimaryKeySelective(oldQuartzjob);
		//先删除旧任务
		QuartzManager.removeJob(oldQuartzjob.getJobname());
		//添加新任务
		QuartzManager.addJob(oldQuartzjob.getJobname(), RollcallJob.class, oldQuartzjob.getCronexpression());
		
		responseJson.put("flag", "1");//
		responseJson.put("msg", "操作成功");
		return responseJson;
	}
    
	/**
	 * 删除
	 * @return
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value="/delete")
	public Map<String,Object> delete(Quartzjob form) {
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		
		Quartzjob quartzjob = quartzjobDao.selectByPrimaryKey(form.getId());
		
		//删除材料
		quartzjobDao.deleteByPrimaryKey(form.getId());
		
		//先删除旧任务
		QuartzManager.removeJob(quartzjob.getJobname());
		
		responseJson.put("flag", "1");//删除成功
		responseJson.put("msg", "操作成功");
		
		return responseJson;
	}
	
	
	/**
	 * 关闭暂停
	 * @return
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value="/pauseJob")
	public Map<String,Object> pauseJob(Quartzjob form) {
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		
		Quartzjob quartzjob = quartzjobDao.selectByPrimaryKey(form.getId());
		
		quartzjob.setJobstatus("关闭");
		
		//关闭
		quartzjobDao.updateByPrimaryKeySelective(quartzjob);
		
		//删除任务
		QuartzManager.removeJob(quartzjob.getJobname());
		
		responseJson.put("flag", "1");//删除成功
		responseJson.put("msg", "操作成功");
		
		return responseJson;
	}
	
	/**
	 * 开启任务
	 * @return
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value="/resumeJob")
	public Map<String,Object> resumeJob(Quartzjob form) {
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		
		Quartzjob quartzjob = quartzjobDao.selectByPrimaryKey(form.getId());
		
		quartzjob.setJobstatus("开启");
		
		//开启
		quartzjobDao.updateByPrimaryKeySelective(quartzjob);
		
		//添加任务
		QuartzManager.addJob(quartzjob.getJobname(), RollcallJob.class, quartzjob.getCronexpression());
		
		responseJson.put("flag", "1");//删除成功
		responseJson.put("msg", "操作成功");
		
		return responseJson;
	}
	
}
